package com.lingyue.entity.sharding;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.Date;
import java.util.Map;

/**
 * @version 1.0.0
 * @author: lzy
 * @date: 2019/12/17 14:50
 */
@Slf4j
public class CustomizedShardingAlgorithm implements PreciseShardingAlgorithm {

    private static Map<Long, String> dealerCache;

    public static Map<Long, String> getDealerCache() {
        return dealerCache;
    }

    public static void setDealerCache(Map<Long, String> dealerCache) {
        log.info("{}.dealerCache refresh  at {}", CustomizedShardingAlgorithm.class.getName(), new Date());
        CustomizedShardingAlgorithm.dealerCache = dealerCache;
    }

    @Override
    public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {
        if (log.isDebugEnabled()) {
            log.debug("分片dealerId:{}", shardingValue.getValue().toString());
        }
        return dealerCache.getOrDefault(Long.valueOf(shardingValue.getValue().toString()), "ds5");
    }

}
